//创建用户小仓库
import { defineStore } from 'pinia'
// 引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index'
//apiusertype
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
//usertype
import type { UserState } from './types/type'
//设置token
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//路由常量
import { routes, asyncRoute, anyRoute } from '@/router/routes'
//路由递归过滤方法
function vncRoute(asyncRoutes: any, resultRoute: any) {
  return asyncRoutes.filter((items: any) => {
    if (resultRoute.includes(items.name)) {
      if (items.children && items.children.length > 0) {
        //这里出现了赋值操作，是浅拷贝会影响源数组的数据完整
        items.children = vncRoute(items.children, resultRoute)
      }
      return true
    }
  })
}
import router from '@/router'
//引入lodash进行深拷贝，因为JSON序列的拷贝也会导致数据不完整
import cloneDeep from 'lodash/cloneDeep'
let useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: routes, //存储生成菜单需要的路由
      avatar: '',
      username: '',
      btnArr: [],
    }
  },
  //异步调用逻辑的地方
  actions: {
    async userLogin(obj: loginFormData) {
      const result: loginResponseData = await reqLogin(obj)
      if (result.code == 200) {
        this.token = result.data
        //本地存储
        SET_TOKEN(result.data as string)
        //返回成功
        return 'ok'
      } else {
        return Promise.reject(
          new Error(result.data || ('用户名无效' as string)),
        )
      }
    },
    async userInfoAction() {
      let result: userInfoResponseData = await reqUserInfo()
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        // 调用递归路由实现根据返回的用户路由限制页面的显示
        let re = vncRoute(cloneDeep(asyncRoute), result.data.routes)
        //返会路由给仓库展示此时路由里面还没有这些页面，只能展示不能用
        this.menuRoutes = [...routes, ...re, ...anyRoute]
        ;[...re, ...anyRoute].forEach((item) => {
          router.addRoute(item)
        })
        this.btnArr = result.data.buttons
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async userLogOut() {
      const result = await reqLogout()
      if (result.ok) {
        REMOVE_TOKEN(),
          (this.token = ''),
          (this.avatar = ''),
          (this.username = '')
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

// 对外暴露
export default useUserStore
